package de.lighti.starcraft.network;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

public class ByteBufferBackedInputStream extends InputStream {

    public static ByteBuffer readStreamInputBuffer( InputStream input ) throws IOException {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();

        final byte[] buf = new byte[4096];
        while (true) {
            final int n = input.read( buf );
            if (n < 0) {
                break;
            }
            baos.write( buf, 0, n );
        }
        input.close();
        return ByteBuffer.wrap( baos.toByteArray() );
    }

    private final ByteBuffer buf;

    public ByteBufferBackedInputStream( ByteBuffer buf ) {
        this.buf = buf;
    }

    @Override
    public int read() throws IOException {
        if (!buf.hasRemaining()) {
            return -1;
        }
        return buf.get() & 0xFF;
    }

    @Override
    public int read( byte[] bytes, int off, int len ) throws IOException {
        if (!buf.hasRemaining()) {
            return -1;
        }

        len = Math.min( len, buf.remaining() );
        buf.get( bytes, off, len );
        return len;
    }
}